package javase.jmx.security.simple.server;

import java.util.HashMap;

import javase.jmx.security.simple.utils.ResourceHelper;

import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.remote.JMXConnectorServer;
import javax.management.remote.JMXConnectorServerFactory;
import javax.management.remote.JMXServiceURL;
import javax.management.remote.rmi.RMIConnectorServer;
import javax.rmi.ssl.SslRMIClientSocketFactory;
import javax.rmi.ssl.SslRMIServerSocketFactory;

public class Server {
// don't forget run rmi registry <JAVA_HOME>/bin/rmiregistry.exe 9999
    @SuppressWarnings({ "unchecked", "rawtypes" })
	public static void main(String[] args) throws Exception {
    
    	System.out.println("Create the MBean server");
        MBeanServer mbs = MBeanServerFactory.createMBeanServer();
        System.out.println("Initialize the environment map");
        HashMap env = new HashMap();
        // Provide SSL-based RMI socket factories.
        SslRMIClientSocketFactory clientSocketFactory = new SslRMIClientSocketFactory();
        SslRMIServerSocketFactory serverSocketFactory = new SslRMIServerSocketFactory();
        env.put(RMIConnectorServer.RMI_CLIENT_SOCKET_FACTORY_ATTRIBUTE, clientSocketFactory);
        env.put(RMIConnectorServer.RMI_SERVER_SOCKET_FACTORY_ATTRIBUTE, serverSocketFactory);
        env.put("jmx.remote.x.password.file", getPathToPasswordProperies());
        env.put("jmx.remote.x.access.file", getPathToAccessProperies());
        env.put("javax.net.ssl.keyStore", getPathToKeystore());
        env.put("javax.net.ssl.keyStorePassword", "password");
        System.out.println("Create an RMI connector server");
        JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://:9999/server");
        JMXConnectorServer connectorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, env, mbs);
        System.out.println("Start the RMI connector server");
        connectorServer.start();
        System.out.println("RMI connector server successfully started");
        System.out.println("Waiting for incoming connections...");
    }
    
    private static String getPathToAccessProperies() {
    	return ResourceHelper.getResourceLocation("javase/jmx/security/simple/config/access.properties");
    }
    
    private static String getPathToPasswordProperies() {
    	return ResourceHelper.getResourceLocation("javase/jmx/security/simple/config/password.properties");
    }
    
    private static String getPathToKeystore() {
    	return ResourceHelper.getResourceLocation("javase/jmx/security/simple/config/keystore");
    }
    
}
